package com.heima.search.controller.v1;

import com.alibaba.fastjson.JSON;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ArticleSearchService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 把所有的文章信息插入到es索引库中去
 */
@RestController
@RequestMapping
public class TextController {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ArticleFeign articleFeign;
    @PostMapping("/insert")
    public String search() throws IOException {
        List<ApArticle> all = articleFeign.findAll();
        List<Map> allArticle=new ArrayList<>();
        for (ApArticle apArticle : all) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("authorId", apArticle.getAuthorId());
            map.put("id", apArticle.getId().toString());
            map.put("images", apArticle.getImages());
            map.put("layout", apArticle.getLayout());
            map.put("publishTime", apArticle.getPublishTime());
            map.put("tag","article");
            map.put("title", apArticle.getTitle());
            allArticle.add(map);
        }
        // 1.创建BulkRequest对象
        BulkRequest bulkRequest = new BulkRequest();
        // 2.创建多个IndexRequest对象，并添加到BulkRequest中
        for (Map map : allArticle) {
            bulkRequest.add(new IndexRequest("app_info_article")
                    .id(map.get("id").toString())     //指定当前的id
                    .source(JSON.toJSONString(map), XContentType.JSON)
            );
        }
        // 3.发起请求
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("status: " + bulkResponse.status());
        return "ok";
    }
}
